﻿using System.Text.Json;
using PC_Touch.DataOP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Numerics;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Data.SQLite;

namespace PC_Touch
{
    public partial class CollectionConfig : Form
    {
        public CollectionConfig()
        {
            InitializeComponent();
            x = this.Width;
            y = this.Height;
            setTag(this);
            this.Resize += new System.EventHandler(this.IOMonitor_Resize);
            GlobalVariable._ConsoleOutputService.OnConsoleOutput += MessageShow;

        }
        private void CollectionConfig_FormClosing(object sender, FormClosingEventArgs e)
        {
            GlobalVariable._ConsoleOutputService.OnConsoleOutput -= MessageShow;
        }
        private void IOMonitor_Load(object sender, EventArgs e)
        {
            ReadMachineJson();
            ReadDBParameter();
            dateTimePicker1.Value = DateTime.Now.AddDays(-7);
        }
        private Task MessageShow(string msg )
        {
            uiRichTextBox1.Invoke((MethodInvoker)(() =>
            {
                uiRichTextBox1.AppendText(msg);
                uiRichTextBox1.SelectionStart = uiRichTextBox1.TextLength;
                uiRichTextBox1.ScrollToCaret();
            }));
            return Task.CompletedTask;
        }
        JsonMachine jsonMachine;
        private void ReadMachineJson()
        {
            jsonMachine = JsonSerializer.Deserialize<JsonMachine>(File.ReadAllText(Environment.CurrentDirectory + @"/AppConfig/Machine.Json", Encoding.UTF8));
        }
        private void WriteMachineJson()
        {
            string json = JsonSerializer.Serialize(jsonMachine);
            File.WriteAllText(Environment.CurrentDirectory + @"/AppConfig/Machine.Json", json, Encoding.UTF8);
        }
        private void ReadDBParameter()
        {
           dataGridView1.DataSource = new object[1];
           string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
           var helper = new SQLiteHelper<CollectionManagement>(connectionString);
           Func<IDataRecord, CollectionManagement> map = record =>
                       new CollectionManagement
                       {
                           id = record.GetInt32(0),
                           createDataTime = record.GetString(1),
                           parameterName = record.GetString(2),
                           parameterAddress = record.GetString(3),
                           parameterType = record.GetString(4),
                           parameterLength = record.GetInt32(5),
                           factor = record.GetDouble(6),
                           unit = !record.IsDBNull(7) ? record.GetString(7):"",
                           eventId =record.GetInt32(8),
                           eventName = !record.IsDBNull(9) ? record.GetString(9):"",
                           triggerAddress = record.GetString(10),
                       };
           var value = helper.Query("SELECT [CollectionManagement].id,[CollectionManagement].createDataTime,parameterName,parameterAddress,parameterType,parameterLength,factor,unit,EventManagement.id AS eventId,eventName,variableAddress FROM CollectionManagement INNER JOIN EventManagement ON CollectionManagement.eventId = EventManagement.id", map);
            dataGridView1.DataSource = new BindingList<CollectionManagement>(value);
            dataGridView1.AllowUserToAddRows = true; // 允许添加新行
            dataGridView1.AllowUserToDeleteRows = true; // 允许删除行
            dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter; // 设置编辑模式
            dataGridView1.Columns[0].ReadOnly = true;
            dataGridView1.Columns[1].ReadOnly = true;
            dataGridView1.Columns[8].ReadOnly = true;
            dataGridView1.Columns[9].ReadOnly = true;
            dataGridView1.DefaultCellStyle.Font = new Font("Arial", 10, FontStyle.Regular);
            dataGridView1.Columns[1].DefaultCellStyle.Font = new Font("Arial", 8, FontStyle.Bold);
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            // 可选：设置列标题的字体
            dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Arial", 12, FontStyle.Bold);
            DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();
            comboBoxColumn.Name = "parameterType";
            comboBoxColumn.HeaderText = "parameterType";
            comboBoxColumn.DataPropertyName = "parameterType"; // 数据绑定的列名
            dataGridView1.Columns.RemoveAt(4); // 移除原来的列
            dataGridView1.Columns.Insert(4, comboBoxColumn); // 插入新的下拉列
            List<string> categories = new List<string> { "Bool", "Short", "Int","Float","String" };
            comboBoxColumn.DataSource = categories;

            DataGridViewComboBoxColumn comboBoxColumnEv = new DataGridViewComboBoxColumn();
            comboBoxColumnEv.DataPropertyName = "eventId"; // 绑定到数据源中对应的外键列
            comboBoxColumnEv.DisplayMember = "eventName"; // 显示在下拉列表中的文本
            comboBoxColumnEv.ValueMember = "eventId"; // 下拉列表的值
            comboBoxColumnEv.HeaderText = "eventName"; // 列标题
            dataGridView1.Columns.RemoveAt(8);

            dataGridView1.Columns.Insert(2, comboBoxColumnEv);
            var helper1 = new SQLiteHelper<EventSelectItem>(connectionString);
            Func<IDataRecord, EventSelectItem> mapEventName = record =>
                        new EventSelectItem
                        {
                            eventId = record.GetInt32(0),
                            eventName = !record.IsDBNull(1) ? record.GetString(1) : "",
                        };
            var value1 = helper1.Query("SELECT id,eventName FROM EventManagement", mapEventName);
            comboBoxColumnEv.DataSource = new BindingList<EventSelectItem>(value1);

            dataCount = dataGridView1.Rows.Count;
        }
        int dataCount = 0 ;
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            var row = dataGridView1.Rows[e.RowIndex];
            var p = row.DataBoundItem as CollectionManagement;
            string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
            CollectionManagementOP op = new CollectionManagementOP(connectionString);
            if (p.eventId!=0)
            {
                if (dataGridView1.Rows.Count > dataCount || dataGridView1.Rows.Count == 0)
                {
                    op.AddParameterToDatabase(p);
                }
                else
                {
                    op.UpdateParameterInDatabase(p);
                }
                ReadDBParameter();
            }
           
        }

        private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this row?", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var p = e.Row.DataBoundItem as CollectionManagement;
                string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
                CollectionManagementOP op = new CollectionManagementOP(connectionString);
                op.DeleteParameterFromDatabase(p);
            }
        }

        #region 控件大小随窗体大小等比例缩放
        private float x = 1;//定义当前窗体的宽度
        private float y = 1;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        private void IOMonitor_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }

        #endregion

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            dataGridView2.DataSource = new object[1];
            string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
            var helper = new SQLiteHelper<CollectionValue>(connectionString);
            Func<IDataRecord, CollectionValue> map = record =>
                        new CollectionValue
                        {
                            id = record.GetInt32(0),
                            createDataTime = record.GetString(1),
                            parameterName = record.GetString(2),
                            parameterValue = record.GetString(3),
                            unit = !record.IsDBNull(4) ? record.GetString(4) : "",
                            triggerValue = record.GetString(5),
                        };
            var value = helper.Query($"SELECT [CollectionValue].id,[CollectionValue].createDataTime,[CollectionManagement].parameterName,parameterValue,[CollectionManagement].unit,triggerValue FROM CollectionValue INNER JOIN CollectionManagement ON CollectionValue.parameterId = CollectionManagement.id WHERE [CollectionValue].createDataTime BETWEEN '{dateTimePicker1.Value.ToString("yyyy - MM - dd 00:00:00")}' AND '{dateTimePicker2.Value.Date.Add(new TimeSpan(23, 59, 59))}' order by [CollectionValue].id DESC", map);
            dataGridView2.DataSource = new BindingList<CollectionValue>(value);
            dataGridView2.DefaultCellStyle.Font = new Font("Arial", 10, FontStyle.Regular);
            dataGridView2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView2.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView2.ColumnHeadersDefaultCellStyle.Font = new Font("Arial", 12, FontStyle.Bold);
            label14.Text = (dataGridView2.RowCount - 1).ToString();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            // 创建一个SaveFileDialog，用于让用户选择保存CSV文件的路径
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV (*.csv)|*.csv";
            sfd.FileName = "Export.csv"; // 默认文件名
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                // 使用StreamWriter来写入CSV文件
                using (StreamWriter sw = new StreamWriter(sfd.FileName, false, Encoding.UTF8))
                {
                    // 写入列标题
                    for (int i = 0; i < dataGridView2.Columns.Count; i++)
                    {
                        sw.Write(dataGridView2.Columns[i].HeaderText);
                        if (i < dataGridView2.Columns.Count - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.WriteLine();

                    // 写入数据行
                    for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)
                    {
                        for (int j = 0; j < dataGridView2.Columns.Count; j++)
                        {
                            sw.Write(dataGridView2.Rows[i].Cells[j].Value.ToString());
                            if (j < dataGridView2.Columns.Count - 1)
                            {
                                sw.Write(",");
                            }
                        }
                        sw.WriteLine();
                    }
                }
                MessageBox.Show("successful ！");
            }
        }

        private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0) // 确保点击的是有效单元格
            {
                button1.Visible = true;
                chartTimeSeries.Visible = true;
                ShowTimeSeriesChart(e.RowIndex);
            }
        }
        private void ShowTimeSeriesChart(int rowIndex)
        {
            // 假设第一列是数据名，第二列是时间戳，第三列是对应的值
            string dataName = dataGridView2.Rows[rowIndex].Cells[2].Value.ToString();
           // DateTime startTime = dateTimePicker1.Value;
           // DateTime endTime = startTime.AddHours(8); // 根据需求调整时间范围

            // 查询时间范围内的数据
            var timeSeriesData = GetDataInRange(dataName);

            // 显示图表
            DisplayChart(timeSeriesData, dataName);
        }
        private List<(DateTime Time, double Value)> GetDataInRange(string dataName)
        {
            // 模拟从数据源获取数据的过程
            // 实际应用中应该替换为真实的数据库查询或其他数据获取逻辑
            string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
            var helper = new SQLiteHelper<CollectionValue>(connectionString);
            Func<IDataRecord, CollectionValue> map = record =>
                        new CollectionValue
                        {
                            id = record.GetInt32(0),
                            createDataTime = record.GetString(1),
                            parameterName = record.GetString(2),
                            parameterValue = record.GetString(3),
                            unit = !record.IsDBNull(4) ? record.GetString(4) : "",
                            triggerValue = record.GetString(5),
                        };
            var value = helper.Query($"SELECT [CollectionValue].id,[CollectionValue].createDataTime,[CollectionManagement].parameterName,parameterValue,[CollectionManagement].unit,triggerValue FROM CollectionValue INNER JOIN CollectionManagement ON CollectionValue.parameterId = CollectionManagement.id WHERE [CollectionManagement].parameterName='{dataName}' AND ([CollectionValue].createDataTime BETWEEN '{dateTimePicker1.Value.ToString("yyyy - MM - dd 00:00:00")}' AND '{dateTimePicker2.Value.Date.Add(new TimeSpan(23, 59, 59))}') order by [CollectionValue].id DESC", map);
            var mockData = new List<(DateTime Time, double Value)>
            {
            };
            try
            {
                foreach (var item in value)
                {
                    mockData.Add((DateTime.Parse(item.createDataTime), double.Parse(item.parameterValue)));
                }
            }
            catch (Exception)
            {
            }
            return mockData;
        }
        private void DisplayChart(List<(DateTime Time, double Value)> data, string seriesName)
        {
            // 清除现有系列
            chartTimeSeries.Series.Clear();
            chartTimeSeries.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd HH:mm:ss";
            // 添加新的系列
            var series = new System.Windows.Forms.DataVisualization.Charting.Series
            {
                Name = seriesName,
                Color = System.Drawing.Color.Blue,
                BorderWidth = 2,
                ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
            };

            // 添加数据点
            foreach (var point in data)
            {
                series.Points.AddXY(point.Time, point.Value);
            }

            // 将新系列添加到图表
            chartTimeSeries.Series.Add(series);

            // 设置图表区域属性（如果需要）
            chartTimeSeries.ChartAreas[0].AxisX.Title = "时间";
            chartTimeSeries.ChartAreas[0].AxisY.Title = "值";

            // 显示图表控件
            chartTimeSeries.Visible = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Visible = false;
            chartTimeSeries.Visible = false;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

}
